<template>
  <div class="app-container calendar-list-container">
    <router-link :to="{name:'hospital_list'}">
      <el-button type="primary" v-waves>返回</el-button>
    </router-link>
    <el-form
      style="width:600px"
      :rules="addRules"
      :model="addQuery"
      status-icon
      ref="addForm"
      label-width="150px"
    >
      <el-form-item label="医院名称" prop="hospitalName">
        <el-input
          type="text"
          v-model="addQuery.hospitalName"
          placeholder="请输入医院名称"
          auto-complete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="所在地区" required>
        <pcq
          :proviceId.sync="addQuery.province"
          :cityId.sync="addQuery.city"
          :areaId.sync="addQuery.area"
        ></pcq>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input type="textarea" v-model="addQuery.address" placeholder="请输入详细地址"></el-input>
      </el-form-item>
      <el-form-item label="押金金额" prop="deposit">
        <el-input-number v-model="addQuery.deposit" :precision="2" :min="1" :max="1000" placeholder="请输入押金金额"></el-input-number>
        <el-txt style="color:#F56C6C">（可支持小数点后两位）</el-txt>
        <!-- <el-input type="text" v-model.number="addQuery.deposit" placeholder="请输入押金金额" autocomplete="off"></el-input> -->
      </el-form-item>
      <el-form-item 
        :label="item.label" 
        prop="" 
        v-for="(item,index) in managerList"
        :key=index
      >
        <el-select
          style="width: 100%;width:300px;margin-right:8px;"
          placeholder="请选择管理员"
          class="filter-item"
          v-model="item.managerName"
          @change="managerChange"
        >
          <el-option
            v-for="(item1,index1) in item.list"
            :label="item1.managerName"
            :value="item1.managerName"
            :key="index1"
          />
        </el-select>
        <el-button type="success" v-waves style="display:inline-block;" @click="setManagerId(item)">确定</el-button>
        <el-button type="warning" v-waves style="display:inline-block;" v-if="item.showNext"  @click="getManagerList(1)">下一级</el-button>
      </el-form-item>
      <el-form-item label="" prop="" v-show="tipText">
        <span style="color:#888">{{tipText}}</span>
      </el-form-item>
      <el-form-item label="当前选择的代理商" prop="managerId">
        <el-input type="text" v-model="nowManager.managerName" disabled></el-input>
      </el-form-item>
      <!-- <el-form-item label="管理员分成比例" v-if="isShow">
        <el-input v-model="managerCommissionRatio" disabled></el-input>
      </el-form-item> -->
    </el-form>
    <el-button size="small" type="primary" @click="submitForm">新增</el-button>
  </div>
</template>
<script>
import { 
  getAddressByAreaId, 
  getId, 
  getAddress
} from "@/utils/getAddress";
import { 
  setHospital, 
  managerList 
} from "@/api/hospital";
import pcq from "@/components/index";
export default {
  name: "hospital_add",
  components: {
    pcq
  },
  data() {
    return {
      addQuery: {
        hospitalName: "",
        province: "",
        city: "",
        address: "",
        managerId: "",
        deposit:''
      },
      addRules: {
        hospitalName: [
          { required: true, message: "请输入医院名称", trigger: "blur" }
        ],
        // managerId: [
        //   { required: true, message: "请选择管理员", trigger: "change" }
        // ],
        area: [
          { required: true, message: "请选择所在地区", trigger: "change" }
        ],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" }
        ],
        deposit:[
          { required: true, message: "请输入押金金额", trigger: "blur" },
          { type: 'number', message: "押金金额必须为数字", trigger: "blur" }
        ]
      },
      provices: [],
      cities: [],
      areas: [],
      pId: "",
      cId: "",
      managerList:[],
      lastManagerId:'',
      nowManager:{},
      tipText:'',
      chooseLevel:0,
    };
  },
  created() {
    (this.provices = getAddressByAreaId(0)), this.getCities();
    this.getAreas();
    this.getManagerList();
  },
  methods: {
    // 点击添加医院
    submitForm() {
      if(!this.nowManager.managerId){
        this.$message({
          message: '请先选择管理员',
          type: 'warning'
        });
        return
      }
      this.$refs["addForm"].validate(async valid => {
        if (valid) {
          let query = {
            hospitalName: this.addQuery.hospitalName,
            address: this.addQuery.address,
            province: getAddress(this.addQuery.province),
            city: getAddress(this.addQuery.city),
            area: getAddress(this.addQuery.area),
            managerId: this.nowManager.managerId,
            deposit: this.addQuery.deposit
          };

          const res = await setHospital(query);
          if (res.code === 1) {
            this.$message.success("新增医院成功");
            this.$router.push({
              name: "hospital_list",
              query: { hospitalId: this.hospitalId }
            });
            this.clearManager()
            this.$refs["addForm"].resetFields();
          }
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    },
    //获取管理员下拉列表 (下一级按钮触发事件)
    async getManagerList(type) {
      const len = this.managerList.length

      if(type == 1 && !this.lastManagerId){
        this.$message({
          message: '请先选择代理商',
          type: 'warning'
        });
        return
      }

      if(type == 1 && !this.managerList[len-1].managerName){
        this.$message({
          message: '请先选择代理商',
          type: 'warning'
        });
        return
      }
      var obj = type == 1 ? {managerId: this.lastManagerId} : {}
      const data = await managerList(obj);
      if(data.code == 1){
        if(data.data.length == 0){
          this.managerList[len-1].showNext = false
          this.tipText="这是最后一级了~"
          return
        }
        var _aa = {}
        _aa.list = data.data //下拉列表数据
        _aa.showNext = true // 是否有下级
        _aa.level = data.data[0].managerLevel // 代理等级
        _aa.label = _aa.level+"级代理" // 代理等级展示文字
        _aa.managerId = ''
        _aa.managerName = ''
        this.managerList.push(_aa);
      }
    },
    // 代理商下拉列表改变时触发事件
    managerChange(chooseTxt){
      const _chooseId = ''
      this.managerList.map(item => {
        item.list.map(_item => {
          if(_item.managerName == chooseTxt){
            this.lastManagerId = _item.managerId
            item.managerId = _item.managerId
            this.chooseLevel = _item.managerLevel
            if(item.list.length == 0){
              this.tipText="这是最后一级了~"
              item.showNext = false
            }else{
              this.tipText=""
              item.showNext = true
            }
            return
          }
        })
      })
      // 清掉后面的等级
      if(this.managerList.length > this.chooseLevel){
        var num = this.managerList.length - this.chooseLevel
        this.managerList.splice(1,num)
        this.tipText=""
        this.managerList.map(item => {
          item.showNext = true
        })
      }
    },
    // 选择当前代理商
    setManagerId(obj){
      if(!obj.managerName){
        this.$message({
          message: '请先选择代理商',
          type: 'warning'
        });
        return
      }
      this.nowManager.managerName = obj.managerName
      this.nowManager.managerId = obj.managerId
      this.$forceUpdate()
    },
    // 格式化选择管理员等相关数据
    clearManager(){ 
      this.nowManager = {}
      this.lastManagerId = ''
    },
    
    //根据fid 查询省、市、区  fid = 0 查询所有省；查询市或者地区 fid 传对应的省areaID
    getAddressByAreaId(fid) {
      return getAddressByAreaId(fid);
    },
    // 获取对应市Id
    getCities() {
      this.addQuery.area = "";
      this.areas = [];
      this.cities = getAddressByAreaId(this.pId);
    },
    // 获取对应的地区
    getAreas() {
      this.addQuery.area = "";
      this.areas = getAddressByAreaId(this.cId);
    }
  }
};
</script>
